package com.coin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.coin.feignclient.*;
import com.coin.geet.*;
import com.coin.model.*;
import com.coin.service.LoginService;
import com.coin.util.IpUtil;
import org.springframework.beans.factory.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 李 力
 * @Date: 2025/6/9
 * @Description: com.coin.service.impl
 * @version: 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basic;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private GeetestLib geetestLib;

    /**
     * @Description: 会员的登录
     * @Author: 李 力
     * @Date: 2025/6/9
     * @Param: loginForm
     * @return: R
     */
    @Override
    public LoginUser login(LoginForm loginForm) {
        //1.参数校验
//        checkFormParam(loginForm);
        //2.远程调用授权接口
        ResponseEntity<JwtToken> tokenResponse = oAuth2FeignClient.getToken("password", loginForm.getUsername(),
                loginForm.getPassword(), "member_type", basic);
        LoginUser loginUser = null;
        if (tokenResponse.getStatusCode() == HttpStatus.OK) {
            JwtToken jwtToken = tokenResponse.getBody();
            loginUser = new LoginUser(loginForm.getUsername(), jwtToken.getExpiresIn(), jwtToken.getTokenType() + " " + jwtToken.getAccessToken(), jwtToken.getRefreshToken());
            redisTemplate.opsForValue().set(jwtToken.getAccessToken(), "", jwtToken.getExpiresIn(), TimeUnit.SECONDS);
        }
        return loginUser;
    }

    private void checkFormParam(LoginForm loginForm) {
        if (loginForm == null) {
            throw new RuntimeException("参数为空");
        }
        if (StrUtil.isEmpty(loginForm.getUsername()) || StrUtil.isEmpty(loginForm.getPassword())
        ) {
            throw new RuntimeException("用户名或者密码为空或其他必要参数为空");
        }
        String challenge = loginForm.getGeetest_challenge();
        String validate = loginForm.getGeetest_validate();
        String seccode = loginForm.getGeetest_seccode();
        String statusStr = redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY + ":" + loginForm.getUuid()).toString();
        int status = Integer.valueOf(statusStr).intValue();
        String userId = redisTemplate.opsForValue().get(GeetestLib.GEETEST_SERVER_USER_KEY + ":" + loginForm.getUuid()).toString();
        GeetestLibResult result = null;
        if (status == 1) {
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("user_id", userId);
            paramMap.put("client_type", "web");
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            paramMap.put("ip_address", IpUtil.getIpAddr(servletRequestAttributes.getRequest()));
            result = geetestLib.successValidate(challenge, validate, seccode, paramMap);
        } else {
            result = geetestLib.failValidate(challenge, validate, seccode);
        }
        if (result.getStatus() != 1) {
            throw new IllegalArgumentException("验证码验证异常");
        }
    }
}
